/* ----------------------------------------------------------------------------
 * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved.
 * Description: Mutex Debug
 * Author: huangjieliang
 * Create: 2013-01-01
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * --------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------------
 * Notice of Export Control Law
 * ===============================================
 * Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 * include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 * applicable export control laws and regulations.
 * --------------------------------------------------------------------------- */

#include "los_typedef.h"
#include "los_hw_pri.h"
#include "los_mux_debug_pri.h"
#include "los_task.h"
#ifdef LOSCFG_SHELL
#include "shcmd.h"
#endif /* LOSCFG_SHELL */

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* __cplusplus */

#ifdef LOSCFG_DEBUG_MUTEX
typedef struct {
    VOID    *creater;       /**< The task entry who created this mutex  */
    UINT64  lastAccessTime; /**< The last access time                   */
} MuxDebugCB;

STATIC MuxDebugCB *g_muxDebugArray;

STATIC VOID osArraySortByTime(UINT32 *sortArray, UINT32 start, UINT32 end)
{
    UINT32 left = start;
    UINT32 right = end;
    UINT32 idx = start;
    UINT32 pivot = sortArray[start];

    while (left < right) {
        while (left < right &&
               g_muxDebugArray[sortArray[right]].lastAccessTime > g_muxDebugArray[pivot].lastAccessTime) {
            right--;
        }

        if (left < right) {
            sortArray[left] = sortArray[right];
            idx = right;
            left++;
        }

        while (left < right &&
               g_muxDebugArray[sortArray[right]].lastAccessTime > g_muxDebugArray[pivot].lastAccessTime) {
            left++;
        }

        if (left < right) {
            sortArray[right] = sortArray[left];
            idx = left;
            right--;
        }
    }

    sortArray[idx] = pivot;

    if (start < idx) {
        osArraySortByTime(sortArray, start, idx - 1);
    }
    if (idx < end) {
        osArraySortByTime(sortArray, idx + 1, end);
    }
    return;
}

VOID osMuxDbgInit(VOID)
{
    g_muxDebugArray = (MuxDebugCB *)LOS_MemAlloc(m_aucSysMem0, LOSCFG_BASE_IPC_MUX_LIMIT * sizeof(MuxDebugCB));
    if (g_muxDebugArray == NULL) {
        PRINT_ERR("%s: malloc failed!\n", __FUNCTION__);
    }
    return;
}

VOID osMuxDbgTimeUpdate(UINT32 muxID)
{
    MuxDebugCB *muxDebug = &g_muxDebugArray[GET_MUXINDEX(muxID)];
    muxDebug->lastAccessTime = LOS_TickCountGet();
    return;
}

VOID osMuxDbgUpdate(UINT32 muxID, VOID *creater)
{
    MuxDebugCB *muxDebug = &g_muxDebugArray[GET_MUXINDEX(muxID)];
    muxDebug->creater = creater;
    muxDebug->lastAccessTime = LOS_TickCountGet();
    return;
}

VOID osMutexCheck(VOID)
{
    LosMuxCB *muxNode = NULL;
    MuxDebugCB *muxDebugNode = NULL;
    UINT32 index;
    UINT32 count = 0;
    UINT32 *indexArray = (UINT32 *)LOS_MemAlloc((void *)OS_SYS_MEM_ADDR, LOSCFG_BASE_IPC_MUX_LIMIT * sizeof(UINT32));
    LOS_TaskLock();
    for (index = 0; index < LOSCFG_BASE_IPC_MUX_LIMIT; index++) {
        muxNode = GET_MUX(index);
        muxDebugNode = &g_muxDebugArray[index];
        if (muxNode->muxStat != OS_MUX_USED || (muxNode->muxStat == OS_MUX_USED &&
                                                     muxDebugNode->creater == NULL)) {
            continue;
        } else if (muxNode->muxStat == OS_MUX_USED && muxNode->owner == (LosTaskCB *)NULL) {
            PRINTK("Mutex ID <0x%x> may leak, Owner is null, TaskEntry of creater: %p,Latest operation time: 0x%llx\n",
                   muxNode->muxID, muxDebugNode->creater, muxDebugNode->lastAccessTime);
        } else {
            if (indexArray != NULL) {
                *(indexArray + count) = index;
                count++;
            } else {
                PRINTK("Mutex ID <0x%x> may leak, TaskID of owner:0x%x, TaskEntry of owner: %p,"
                    "TaskEntry of creater: %p,Latest operation time: 0x%llx\n",
                    muxNode->muxID, muxNode->owner->taskID, muxNode->owner->taskEntry, muxDebugNode->creater,
                    muxDebugNode->lastAccessTime);
            }
        }
    }
    if (indexArray != NULL) {
        if (count > 0) {
            osArraySortByTime(indexArray, 0, count - 1);
            for (index = 0; index < count; index++) {
                muxNode = GET_MUX(indexArray[index]);
                muxDebugNode = &g_muxDebugArray[indexArray[index]];
                PRINTK("Mutex ID <0x%x> may leak, TaskID of owner:0x%x, TaskEntry of owner: %p,"
                    "TaskEntry of creater: %p,Latest operation time: 0x%llx\n",
                    muxNode->muxID, muxNode->owner->taskID, muxNode->owner->taskEntry, muxDebugNode->creater,
                    muxDebugNode->lastAccessTime);
            }
        }
        LOS_TaskUnlock();
        LOS_MemFree((void *)OS_SYS_MEM_ADDR, indexArray);
        return;
    }
    LOS_TaskUnlock();
    return;
}

#ifdef LOSCFG_SHELL
LITE_OS_SEC_TEXT_MINOR UINT32 osShellCmdMuxInfoGet(UINT32 argc, CHAR **argv)
{
    if (argc > 0) {
        PRINTK("\nUsage: mutex\n");
        return OS_ERROR;
    }
    PRINTK("used mutexs information: \n");
    osMutexCheck();
    return LOS_OK;
}
SHELLCMD_ENTRY(mutex_shellcmd, CMD_TYPE_EX, "mutex", 0, (CMD_CBK_FUNC)osShellCmdMuxInfoGet); /*lint !e19*/
#endif /* LOSCFG_SHELL */
#endif /* LOSCFG_DEBUG_MUTEX */

#ifdef LOSCFG_DEBUG_DEADLOCK
typedef struct {
    LOS_DL_LIST muxListHead;    /**< Task-held mutexs list      */
    UINT64      lastAccessTime; /**< The last operation time    */
} MuxDLinkCB;

typedef struct {
    LOS_DL_LIST muxList;    /**< Insert mutex into the owner task CB    */
    VOID        *muxCB;     /**< The Mutex CB pointer                   */
} MuxDLinkNode;

static MuxDLinkCB *g_muxDeadlockCBArray;

/**
 * Mutex deadlock detection time threshold, will print out task information that has not been scheduled within this time.
 * The unit is tick.
 */
#define OS_MUX_DEADLOCK_CHECK_THRESHOLD 60000

VOID osMuxDlockCheckInit(VOID)
{
    UINT32 index;

    g_muxDeadlockCBArray = (MuxDLinkCB *)LOS_MemAlloc(m_aucSysMem0,
        ((LOSCFG_BASE_CORE_TSK_LIMIT + 1) * sizeof(MuxDLinkCB)));
    if (g_muxDeadlockCBArray == NULL) {
        PRINT_ERR("%s: malloc failed!\n", __FUNCTION__);
        return;
    }

    for (index = 0; index < LOSCFG_BASE_CORE_TSK_LIMIT + 1; index++) {
        g_muxDeadlockCBArray[index].lastAccessTime = 0;
        LOS_ListInit(&g_muxDeadlockCBArray[index].muxListHead);
    }
}

VOID osMuxDlockNodeInsert(UINT32 taskID, VOID *muxCB)
{
    MuxDLinkNode *muxDLNode = NULL;

    if (taskID > LOSCFG_BASE_CORE_TSK_LIMIT || muxCB == NULL) {
        PRINT_ERR("%s: Argument is invalid!\n", __FUNCTION__);
        return;
    }

    muxDLNode = (MuxDLinkNode *)LOS_MemAlloc(m_aucSysMem0, sizeof(MuxDLinkNode));
    if (muxDLNode == NULL) {
        PRINT_ERR("%s: malloc failed!\n", __FUNCTION__);
        return;
    }
    (VOID)memset_s(muxDLNode, sizeof(MuxDLinkNode), 0, sizeof(MuxDLinkNode));
    muxDLNode->muxCB = muxCB;

    LOS_ListTailInsert(&g_muxDeadlockCBArray[taskID].muxListHead, &muxDLNode->muxList);
}

VOID osMuxDlockNodeDelete(UINT32 taskID, VOID *muxCB)
{
    UINT32 index;
    MuxDLinkCB *muxDLCB = NULL;
    LOS_DL_LIST *list = NULL;
    MuxDLinkNode *muxDLNode = NULL;

    if (taskID > LOSCFG_BASE_CORE_TSK_LIMIT || muxCB == NULL) {
        PRINT_ERR("%s: Argument is invalid!\n", __FUNCTION__);
        return;
    }

    muxDLCB = &g_muxDeadlockCBArray[taskID];
    LOS_DL_LIST_FOR_EACH(list, &muxDLCB->muxListHead)
    {
        muxDLNode = LOS_DL_LIST_ENTRY(list, MuxDLinkNode, muxList);
        if (muxDLNode->muxCB == muxCB) {
            LOS_ListDelete(&muxDLNode->muxList);
            (VOID)LOS_MemFree(m_aucSysMem0, muxDLNode);
            return;
        }
    }

    PRINT_ERR("%s: find mutex deadlock node failed!\n", __FUNCTION__);
}

VOID osTaskTimeUpdate(UINT32 taskID, UINT64 tickCount)
{
    if (taskID > LOSCFG_BASE_CORE_TSK_LIMIT) {
        return;
    }

    g_muxDeadlockCBArray[taskID].lastAccessTime = tickCount;
}

extern void BackTraceSub(AARCHPTR);
STATIC VOID osDeadlockBackTrace(LosTaskCB *taskCB)
{
    AARCHPTR FP;
    TSK_CONTEXT_S *context = NULL;

    PRINTK("*******backtrace begin*******\n");
    context = (TSK_CONTEXT_S *)taskCB->stackPointer;
#ifdef __LP64__
    FP = context->aullR[29];  /* X29:FP */
    PRINTK("pc = %p  lr = %p\n", context->ullPC, context->ullLR);
#else
    FP = context->auwR[11];  /* R11:FP */
    PRINTK("pc = %p  lr = %p\n", context->uwPC, context->uwLR);
#endif

    BackTraceSub(FP);

    PRINTK("********backtrace end********\n");
    return;
}

STATIC VOID osMutexPendTaskList(LOS_DL_LIST *list)
{
    LOS_DL_LIST *listTmp = NULL;
    LosTaskCB *pendedTask = NULL;
    UINT32 index = 0;

    LOS_DL_LIST_FOR_EACH(listTmp, list) {
        pendedTask = OS_TCB_FROM_PENDLIST(listTmp);
        if (index == 0) {
            PRINTK("Pended task: %d. name:%-15s, id:0x%-5x\n", index, pendedTask->taskName, pendedTask->taskID);
        } else {
            PRINTK("             %d. name:%-15s, id:0x%-5x\n", index, pendedTask->taskName, pendedTask->taskID);
        }
        index++;
    }
}

static VOID osTaskHoldMutexList(MuxDLinkCB *muxDLCB)
{
    UINT32 index = 0;
    MuxDLinkNode *muxDLNode = NULL;
    LosMuxCB *muxCB = NULL;
    LosTaskCB *ownerTCB = NULL;
    LOS_DL_LIST *list = NULL;
    LOS_DL_LIST *listTmp = NULL;

    if (LOS_ListEmpty(&muxDLCB->muxListHead) == TRUE) {
        PRINTK("null\n");
    } else {
        LOS_DL_LIST_FOR_EACH(list, &muxDLCB->muxListHead)
        {
            muxDLNode = LOS_DL_LIST_ENTRY(list, MuxDLinkNode, muxList);
            muxCB = (LosMuxCB *)muxDLNode->muxCB;
            ownerTCB = muxCB->owner;
            PRINTK("<Mutex%d info>\n", index);
            PRINTK("Ptr handle:%p\n", muxCB);
            PRINTK("Owner:%s\n", ownerTCB->taskName);
            PRINTK("Count:%d\n", muxCB->muxCount);
            listTmp = &muxCB->muxList;
            if (LOS_ListEmpty(listTmp) == FALSE) {
                osMutexPendTaskList(listTmp);
            } else {
                PRINTK("Pended Task: null\n");
            }
            index++;
        }
    }
}

VOID osMutexDlockCheck(VOID)
{
    LosTaskCB *taskCB = NULL;
    UINT32 loop;
    MuxDLinkCB *muxDLCB = NULL;
    UINT32 intSave;

    for (loop = 0; loop < g_taskMaxNum; loop++) {
        taskCB = (((LosTaskCB *)g_taskCBArray) + loop);
        if (taskCB->taskStatus & OS_TASK_STATUS_UNUSED) {
            continue;
        }

        muxDLCB = &g_muxDeadlockCBArray[taskCB->taskID];
        if ((LOS_TickCountGet() - muxDLCB->lastAccessTime) > OS_MUX_DEADLOCK_CHECK_THRESHOLD) {
            intSave = LOS_IntLock();
            PRINTK("Task_name:%s, ID:0x%x, holds the Mutexs below:\n", taskCB->taskName, taskCB->taskID);
            osTaskHoldMutexList(muxDLCB);
            osDeadlockBackTrace(taskCB);
            PRINTK("\n");
            LOS_IntRestore(intSave);
        }
    }
}

#ifdef LOSCFG_SHELL
UINT32 osShellCmdMuxDeadlockCheck(UINT32 argc, CHAR **argv)
{
    if (argc > 0) {
        PRINTK("\nUsage: dlock\n");
        return OS_ERROR;
    }
    PRINTK("Start mutexs deadlock check: \n");
    osMutexDlockCheck();
    PRINTK("-----------End-----------\n");
    return LOS_OK;
}
SHELLCMD_ENTRY(deadlock_shellcmd, CMD_TYPE_EX, "dlock", 0, (CMD_CBK_FUNC)osShellCmdMuxDeadlockCheck); /*lint !e19*/
#endif /* LOSCFG_SHELL */
#endif /* LOSCFG_DEBUG_DEADLOCK */

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */

